package servlets.message;

import hibernate.method.MessageMethods;
import hibernate.util.HibernateUtil;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 * Servlet implementation class Send
 */
@WebServlet(name = "MessageSend", urlPatterns = { "/MessageSend" })
public class Send extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor.
	 */
	public Send() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		PrintWriter out = response.getWriter();
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("utf-8");
		int sender_id = Integer.parseInt((String) request
				.getParameter("sender_id"));
		String subject = (String) request.getParameter("subject");
		String content = (String) request.getParameter("content");
		int receiver_id = Integer.parseInt(request.getParameter("receiver"));
		if (receiver_id == 0) {
			out.println("<script type=\"text/javascript\">alert(\"Nie podales uzytkownika\"); window.location.href = \"social/index.jsp?page=messages&group=newMessage\";</script>");
		} else {
			response.setContentType("text/html");

			SessionFactory sessionFactory = HibernateUtil
					.getSessionAnnotationFactory();
			Session session = sessionFactory.openSession();
			session.beginTransaction();
			MessageMethods msg_m = new MessageMethods();
			msg_m.send(sessionFactory, session, receiver_id, sender_id,
					subject, content);

			try {
				session.getTransaction().commit();
				out.println("<script type=\"text/javascript\">alert(\"Wiadomosc zostala wyslana\"); window.location.href = \"social/index.jsp?page=messages&group=messages_sent\";</script>");
			} catch (Exception e) {
				out.println("<script type=\"text/javascript\">alert(\"Wiadomosc nie zostala wyslana\"); window.location.href = \"social/index.jsp?page=messages&group=newMessage\";</script>");
			}

		}
	}

}
